//
//  HeartHistoryController.swift
//  MoyoungHome
//
//  Created by 易先生 on 2022/9/15.
//

import UIKit
import NSObject_Rx
import RxCocoa
import MYModule


protocol HistoryControllerDelegate {
    
    func didSected(_ vc: HistoryController, model: MYSQLiteTableiabe?)
    
}

class HistoryController: ViewController {

	public var showType: HistoryShowType = .bloodOxygen
    
    public var selectedDelegate: HistoryControllerDelegate?

	public let selectIdRelay = PublishRelay<Int>()
    
    let emptyView = LottieEmptyView()

	override func viewDidLoad() {
		super.viewDidLoad()
        navigation.bar.backgroundColor = UIColor.darkBackground
	}

	override func makeUI() {
		super.makeUI()
        
        switch showType {
        case .bloodOxygen:
            navigation.item.title = "blood_oxygen_title".language
        case .stress:
            navigation.item.title = "stress_title".language
        case .hrv:
            navigation.item.title = "hrv_title".language
        case .heart:
            navigation.item.title = "heart_rate_title".language
        }
        view.backgroundColor =  UIColor.darkBackground
        view.addSubview(tableView)
        
        view.addSubview(emptyView)
        
		tableView.snp.makeConstraints { make in
			make.edges.equalToSuperview()
		}
        
        emptyView.snp.makeConstraints { make in
            make.center.equalTo(tableView.snp.center)
        }
	}

	override func bindViewModel() {
		super.bindViewModel()

        viewModel.historysRelay.subscribe(onNext: { [weak self] isReload in
            guard let self = self else { return }
            guard isReload else {
                return
            }
            
            self.tableView.reloadData()
            
            self.emptyView.isHidden = isReload
            
        }).disposed(by: rx.disposeBag)

	}

	private lazy var viewModel: HistoryViewModel = {
		let viewModel = HistoryViewModel(showType: showType)
		return viewModel
	}()

	private lazy var tableView: TableView = {
		let tableView = TableView(frame: .zero, style: .plain)
        tableView.separatorColor = UIColor.assist_D0D0D0
        tableView.sectionHeaderHeight = 48
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
		tableView.register(HistoryCell.self, forCellReuseIdentifier: HistoryCell.reuseIdentifier)
		return tableView
	}()

}

extension HistoryController: UITableViewDataSource{

    func numberOfSections(in tableView: UITableView) -> Int{
        return viewModel.sections.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return viewModel.sections[section].items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let sections = viewModel.sections[indexPath.section]
        let item = sections.items[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: HistoryCell.reuseIdentifier) as! HistoryCell
        
        var rectCorner: UIRectCorner? = nil
        if indexPath.row == 0 {
            rectCorner = [.topLeft, .topRight]
        } else if indexPath.row == sections.items.count - 1 {
            rectCorner = [.bottomLeft, .bottomRight]
        }
        
        if sections.items.count == 1 {
            rectCorner = .allCorners
        }
        
        switch self.showType {
        case .bloodOxygen:
            cell.bind(to: item, currentNumColor: UIColor.BloodOxygen.theme, until: "%", roundingCorners: rectCorner)
        case .stress:
            cell.bind(to: item, currentNumColor: UIColor.Stress.theme, roundingCorners: rectCorner)
        case .hrv:
            cell.bind(to: item, currentNumColor: UIColor.HRV.theme, until: "unit_hrv".language, roundingCorners: rectCorner)
        case .heart:
            cell.bind(to: item, currentNumColor: UIColor.HeartRate.theme, until: "heart_rate_bpm".language, roundingCorners: rectCorner)
        }
        
        
        return cell
    }
}

extension HistoryController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let title = viewModel.sections[section].title
        let sectionView = View(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 48))
        sectionView.backgroundColor =  UIColor.darkBackground
        let sectionTitleLbael = Label(frame: CGRect(x: 20, y: 16, width: view.bounds.size.width-40, height: 16))
        sectionTitleLbael.font = Fonts.systemFont(ofSize: 14)
        sectionTitleLbael.textColor = UIColor.assist_A9A9A9
        sectionTitleLbael.text = title
        sectionView.addSubview(sectionTitleLbael)
        return sectionView
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        guard let cell = tableView.cellForRow(at: indexPath) as? HistoryCell else {
            return
        }
        
        let model = cell.model
        
        if let selectedDelegate = self.selectedDelegate {
            
            selectedDelegate.didSected(self, model: model)
            return
        }
        
        
        switch self.showType {
        case .bloodOxygen:
            
            pushToBloodOxygenDetailController(model: model)
            return
            
        case .stress:
            
            pushToStressDetailController(model: model)
            return
            
        case .hrv:
            
            pushToHRVDetailController(model: model)
            return
            
        case .heart:
            
            pushToHeartRateHistoryDetailController(model: model)
            return
        }
    }
    
    
    
}

extension HistoryController {
    
    func pushToBloodOxygenDetailController(model: MYSQLiteTableiabe?) {
        
        let vc = BloodOxygenDetailController()
        vc.showRightItem = false
        vc.provider = BloodOxygenProvider(bloodOxggenModel: model as? SingleBloodOxygenModel)
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func pushToStressDetailController(model: MYSQLiteTableiabe?) {
        
        let vc = StressDetailViewController()
        vc.showRightItem = false
        vc.provider = StressProvider(stressModel: model as? SingleStressModel)
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func pushToHRVDetailController(model: MYSQLiteTableiabe?) {
        
        let vc = SingleHRVDetailController()
        vc.showRightItem = false
        vc.provider = SingleHRVProvider(hrvModel: model as? SingleHRVModel)
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func pushToHeartRateHistoryDetailController(model: MYSQLiteTableiabe?) {
        
        let vc = SingleHeartRateDetailController()
        vc.showRightItem = false
        vc.provider = SingleHeartRateProvider(heartRateModel: model as? SingleHeartRateModel)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}
